<?php

namespace app\api\controller;

use app\api\Api;
use app\model\Sms as SmsModel;

class Sms extends Api
{
    public function __construct()
    {
	    //以下字段不允许使用POST修改
		$this -> postBlackList = ['sms_id', "sms_status", "sms_createtime", "sms_updatetime", "sms_system"];
    	//SQL查询的字段 []为所有
    	$this -> selectFieldList = [];
		//筛选条件
		$this -> searchFilter = [
		    "sms_phone"=>"=",//相同筛选
		];
		$this -> per_page = 20;
        parent::__construct();
    }
    /**
     * 发送短信验证码
     *
     * @return void
     */
    public function send()
    {
        $SmsModel = new SmsModel();
        if (!input("captcha") || !input("token")) {
            return jerr( "你的验证码没有填写");
        }
        $captcha = input("captcha");
        $token = input("token");

        if (!captcha_check_api($captcha, $token)) {
            //验证失败
            return jerr( "验证码已过期，请重新刷新验证码");
        }
        if (input("phone")) {
            $phone = input('phone');
            $where = [
                'sms_phone' => $phone,
                'sms_timeout' => [">", time()]
            ];
            $sms = $SmsModel->where($where)->order("sms_createtime desc")->find();
            if ($sms) {
                return jok('你的短信验证码已经发送至你的手机');
            } else {
                $code = rand(100000, 999999);
                $SmsModel->sendSms($phone, $code);
                $SmsModel->insert([
                    "sms_phone" => $phone,
                    "sms_code" => $code,
                    "sms_timeout" => time() + 300,
                    "sms_createtime" => time(),
                    "sms_updatetime" => time(),
                ]);
                return jok('短信验证码已经发送至你的手机');
            }
        } else {
            return jerr( "手机号为必填信息，请填写后提交");
        }
    }
}
